/*
 * Copyright (c) 2009, Hamish Morgan. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice,
 *    this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * 3. Neither the name of the University of Sussex nor the names of its
 *    contributors may be used to endorse or promote products derived from
 *    this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 */
package locusts.server.behaviours;

import java.util.ArrayList;
import java.util.List;
import locusts.common.entities.Actor;
import locusts.common.entities.Entity;
import locusts.common.entities.EntityList;
import locusts.common.entities.EntityType;

/**
 * AbstractFlockBehaviour objects are behaviours that require standard
 * boids style parameters: neighbourhood radius, angle, and a list of
 * vehicles that are in the flock.
 *
 * @author Hamish Morgan Morgan
 */
public abstract class AbstractFlockBehaviour extends AbstractBehaviour {

    private static final double DEFAULT_MIN_DISTANCE = 0d;
    private static final double DEFAULT_MAX_DISTANCE = 100d;
    private static final double DEFAULT_MAX_ANGLE = 0.7 * Math.PI;
    //
    private List<Actor> flock;
    private EntityType flockType;
    private double minDistance = DEFAULT_MIN_DISTANCE;
    private double maxDistance = DEFAULT_MAX_DISTANCE;
    private double maxAngle = DEFAULT_MAX_ANGLE;

    protected AbstractFlockBehaviour(double w, EntityType flockType,
            double minDist, double maxDist, double maxAng) {
        super(w);
        this.flockType = flockType;
        flock = null;
        setMaxAngle(maxAng);
        setMinDistance(minDist);
        setMaxDistance(maxDist);
    }

    protected AbstractFlockBehaviour(double w, EntityType flockType) {
        super(w);
        this.flockType = flockType;
        flock = null;
        setMaxAngle(DEFAULT_MAX_ANGLE);
        setMinDistance(DEFAULT_MIN_DISTANCE);
        setMaxDistance(DEFAULT_MAX_DISTANCE);
    }

    protected AbstractFlockBehaviour(EntityType flockType) {
        super();
        this.flockType = flockType;
        flock = null;
        setMaxAngle(DEFAULT_MAX_ANGLE);
        setMinDistance(DEFAULT_MIN_DISTANCE);
        setMaxDistance(DEFAULT_MAX_DISTANCE);
    }

    public double getMaxDistance() {
        return maxDistance;
    }

    public double getMinDistance() {
        return minDistance;
    }

    public double getMaxAngle() {
        return maxAngle;
    }

    @Override
    public double getWeight() {
        return super.getWeight();
    }

    public void setMaxDistance(double maxDistance) {
        if (Double.isNaN(maxDistance) || Double.isInfinite(maxDistance) ||
                maxDistance < 0)
            throw new IllegalArgumentException();
        if (minDistance >= maxDistance)
            throw new IllegalArgumentException();
        this.maxDistance = maxDistance;
    }

    public void setMinDistance(double minDistance) {
        if (Double.isNaN(minDistance) || Double.isInfinite(minDistance) ||
                minDistance < 0)
            throw new IllegalArgumentException();
        if (minDistance >= maxDistance)
            throw new IllegalArgumentException();
        this.minDistance = minDistance;
    }

    public void setMaxAngle(double maxAngle) {
        if (Double.isNaN(maxAngle) || Double.isInfinite(maxAngle))
            throw new IllegalArgumentException();
        this.maxAngle = maxAngle;
    }

//    public void setFlock(List<Actor> flock) {
////        if (flock == null)
////            throw new IllegalArgumentException();
//        this.flock = flock;
//    }
//
//    public List<Actor> getFlock() {
//        return flock;
//    }

    protected List<Actor> getNeighbors(Actor boid) {
        List<Actor> neighbors = new ArrayList<Actor>();
        if(flock == null)
            return neighbors;

        for (Actor other : flock) {
            if (isNeighbor(boid, other))
                neighbors.add(other);
        }
        return neighbors;
    }

    public boolean isNeighbor(Actor a, Actor b) {
        if (a == null || b == null)
            throw new IllegalArgumentException();
        // this is not a neighbor of itself
        if (b == a)
            return false;

        // check it is within the minimum distance
        final double dx = b.getX() - a.getX();
        if (dx > maxDistance)
            return false;
        final double dy = b.getY() - a.getY();
        if (dy > maxDistance)
            return false;

        double lenSquared = dx * dx + dy * dy;
        if (lenSquared > maxDistance * maxDistance)
            return false;
        if (lenSquared < minDistance * minDistance)
            return false;

        double bearing = a.bearingTo(b);

        if (bearing > maxAngle)
            return false;

        return true;
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;
        final AbstractFlockBehaviour other = (AbstractFlockBehaviour) obj;
        if (this.flock != other.flock &&
                (this.flock == null || !this.flock.equals(other.flock)))
            return false;
        if (this.minDistance != other.minDistance) return false;
        if (this.maxDistance != other.maxDistance) return false;
        if (this.maxAngle != other.maxAngle) return false;
        return super.equals(obj);
    }

    @Override
    public int hashCode() {
        int hash = super.hashCode();
        hash = 89 * hash + (this.flock != null ? this.flock.hashCode() : 0);
        hash = 89 * hash +
                (int) (Double.doubleToLongBits(this.minDistance) ^
                (Double.doubleToLongBits(this.minDistance) >>> 32));
        hash = 89 * hash +
                (int) (Double.doubleToLongBits(this.maxDistance) ^
                (Double.doubleToLongBits(this.maxDistance) >>> 32));
        hash = 89 * hash + (int) (Double.doubleToLongBits(this.maxAngle) ^
                (Double.doubleToLongBits(this.maxAngle) >>> 32));
        return hash;
    }

    @Override
    public void initialize(EntityList entities) {
        super.initialize(entities);
        if(flock != null)
            return;
        flock = entities.getAllByType(flockType, Actor.class);
//        flock = new ArrayList<Actor>();
//        int typeId = flockType.getId();
////        final List<Entity> ents = world.getEntities();
////        synchronized(ents) {
//            for(Entity e : entities) {
//                if(!(e instanceof Actor))
//                    continue;
//                Actor a = (Actor)e;
//                if(a.getTypeId() == typeId)
//                    flock.add(a);
//            }
//        }
    }

    @Override
    public void clean() {
        super.clean();
        flock = null;
    }
}
